package com.office.framework.common;

/**
 * Created by jyyco on 2015/7/23.
 */

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import com.jfinal.log.Logger;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @title: 日志/异常处理拦截器
 * @className: ActionLogInterceptor
 * @description: TODO
 * @company: FOREVEROSS
 * @author: <a href="http://www.smhaochi.com">vakin jiang</a>
 * @createDate: 2014年4月2日
 * @version: 1.0
 */
public class ExceptionAndLogInterceptor implements Interceptor {
    private static final Logger log = Logger.getLogger(ExceptionAndLogInterceptor.class);
    private Result result;



    public void intercept(Invocation ai) {
        Controller controller = (Controller)ai.getController();
        HttpServletRequest request = controller.getRequest();

        boolean successed = false;
        try {
            ai.invoke();
            successed = true;
        } catch (Exception e) {
            //
            doLog(ai,e);
            //判断是否ajax请求
            String header = request.getHeader("X-Requested-With");
            boolean isAjax = "XMLHttpRequest".equalsIgnoreCase(header);
            String msg = formatException(e);
            if(isAjax){
                result.setMessage(msg);
                result.setSuccess(false);
                controller.renderJson(result);
                controller.render("common/_result.html");
            }else{
                String redirctUrl = request.getHeader("referer");
                if(StringUtils.isBlank(redirctUrl)){
                    redirctUrl = request.getRequestURI();
                }
            }
        }finally{
        }
    }
    /**
     * @methodName: doLog
     * @description: 记录log4j日志
     * @author: vakinge
     * @createDate: 2014年4月3日
     * @param ai
     * @param e
     */
    private void doLog(Invocation ai,Exception e) {
        //开发模式
        if(JFinal.me().getConstants().getDevMode()){
            e.printStackTrace();
        }
        //业务异常不记录 ？？
       // if( e instanceof BaseBussException)return;
        StringBuilder sb =new StringBuilder("\n---Exception Log Begin---\n");
        sb.append("Controller:").append(ai.getController().getClass().getName()).append("\n");
        sb.append("Method:").append(ai.getMethodName()).append("\n");
        sb.append("Exception Type:").append(e.getClass().getName()).append("\n");
        sb.append("Exception Details:");
        log.error(sb.toString(), e);
    }
    /**
     * 格式化异常信息，用于友好响应用户
     * @param e
     * @return
     */
    private static String formatException(Exception e){
        String message = null;
        Throwable ourCause = e;
        while ((ourCause = e.getCause()) != null) {
            e = (Exception) ourCause;
        }
        String eClassName = e.getClass().getName();
        //一些常见异常提示
        if("java.lang.NumberFormatException".equals(eClassName)){
            message = "请输入正确的数字";
        }else  {
            //if (e instanceof BaseBussException || e instanceof RuntimeException)
            message = e.getMessage();
            if(StringUtils.isBlank(message))message = e.toString();
        }

        //获取默认异常提示
        if (StringUtils.isBlank(message)){
            message = "系统繁忙,请稍后再试";
        }
        //替换特殊字符
        message = message.replaceAll("\"", "'");
        return message;
    }


    public Result getResult() {
        return result;
    }

    public void setResult(Result result) {
        this.result = result;
    }


}